//
//  UserAccountViewModel.swift
//  mySina
//
//  Created by mac on 15/12/18.
//  Copyright © 2015年 tz. All rights reserved.
//

import UIKit
import AFNetworking
class UserAccountViewModel: NSObject {
    //定义用户模型对应的属性
    var userAccount:UserAccount?
    //对象构造->先构造本类，再构造父类
    override init() {
        userAccount = UserAccount.loadAccount()
        super.init()
    }
    //用户是否登录
    var userLogin:Bool {
        return userAccount?.access_token != nil
    }
    //用户呢称的友好显示
    var userName:String? {
//        print(userAccount?.name)
        return userAccount?.name
    }
    //用户图像的URL
    var headUrl:NSURL? {
        let url = NSURL(string: userAccount?.avatar_large ?? "")
        return url
    }
    //用户的token
    var token:String? {
        return userAccount?.access_token
    }
    //MARK: 加载用户的Token
    func loadAccessToken(code:String,finished:(isSuccess:Bool) -> ()) {
        let urlString = "/oauth2/access_token"
        let parameters = ["client_id":client_id,"client_secret":client_secret,"grant_type":"authorization_code","code":code,"redirect_uri":redirect_uri]
        NetwookTools.sharedTools.requestJSONDict(.POST, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
            if error != nil {
                //执行失败
                finished(isSuccess: false)
                return
            }
            //字典转模型
            let userAccount = UserAccount(dict: dict! )
            self.loadUserInfo(userAccount, finished: finished)
        })
    }
    //MARK: 获取用户信息
    private func loadUserInfo(account:UserAccount,finished:(isSuccess:Bool) -> ()) {
        let urlString = "2/users/show.json"
        if let token = account.access_token,uid = account.uid {
            let parameters = ["access_token":token,"uid":uid]
            
            NetwookTools.sharedTools.requestJSONDict(.GET, urlString: urlString, parameters: parameters, finished: { (dict, error) -> () in
                if error != nil {
                    //执行失败的回调
                    finished(isSuccess: false)
                }
                //获取用户图像
                let avatar_large = dict!["avatar_large"] as! String
                //获取用户友好显示
                let name = dict!["name"] as! String
                //给模型赋值
                account.avatar_large = avatar_large
//                print("ddddd\(avatar_large)")
                account.name = name
//                print("ddddd\(name)")
                //存储用户数据
                account.saveAccount()
                //执行成功的对象
                finished(isSuccess: true)
            })
        }
    }
}
